package com.leo.nio.filechannel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author du
 */
public class NioFileChannelToFile {
    public static void main(String[] args) throws IOException {

        String str = "hello world.";

        // 创建输出流
        // RandomAccessFile, FileInputStream, FileOutputStream 都可以获取文件通道
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");

        // 从输出流获取通道
        FileChannel fileChannel = fileOutputStream.getChannel();

        // 将数据写入创建的ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put(str.getBytes());

        // 写入channel前, 将ByteBuffer改为读模式
        byteBuffer.flip();

        // ByteBuffer写入channel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();
    }
}
